/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.cadoc.parser;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.cadoc.cqe.PatternContext;

public class FileSystemInput implements PatternContext {

	private File rootDir;
	private Collection<File> aggregate;
	private String fileType;

	public FileSystemInput(File rootDir) {

		this.rootDir = rootDir;
		this.fileType = ".java";
	}

	public Iterator<File> iterator() {
		if(aggregate==null){
			try {
				aggregate = getFileListingNoSort(rootDir);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}
		return aggregate.iterator();
	}

	private Collection<File> getFileListingNoSort(File startingDir)
			throws FileNotFoundException {

		List<File> result = new ArrayList<File>();
		File[] filesAndDirs = startingDir.listFiles();
		List<File> filesDirs = Arrays.asList(filesAndDirs);
		for (File file : filesDirs) {
			if(file.isFile() && file.getName().endsWith(fileType)){
				result.add(file); // always add, even if directory
			}else if (!file.isFile()) {
				// must be a directory
				// recursive call!
				Collection<File> deeperList = getFileListingNoSort(file);
				result.addAll(deeperList);
			}
		}
		return result;
	}
/*
	private void validateDirectory(File aDirectory)
			throws FileNotFoundException {
		
		if (aDirectory == null) {
			throw new IllegalArgumentException("Directory should not be null.");
		}
		if (!aDirectory.exists()) {
			throw new FileNotFoundException("Directory does not exist: "
					+ aDirectory);
		}
		if (!aDirectory.isDirectory()) {
			throw new IllegalArgumentException("Is not a directory: "
					+ aDirectory);
		}
		if (!aDirectory.canRead()) {
			throw new IllegalArgumentException("Directory cannot be read: "
					+ aDirectory);
		}
	}
*/
}
